// socket 聊天室单独测试
let util = require('../../utils/util')

Page({
  data: {
    socketOpen: false,
    heartBeatTimeOut: null, // 心跳定时器
    comment: '',
    commentList: [],
  },
  onShow() {
    this.initSocket()
  },
  onHide() {
    wx.closeSocket()
    clearTimeout(this.data.heartBeatTimeOut)
  },
  onUnload() {
    wx.closeSocket()
    clearTimeout(this.data.heartBeatTimeOut)
  },
  // 初始化socket链接
  initSocket() {
    let _this = this
    // 建立连接
    wx.connectSocket({
      url: `ws://172.21.7.51:8088`,
      header: {
        'content-type': 'application/json'
      },
      method: 'GET',
      success(res) {
        console.log('客户端连接！');
        _this.listeningScoket()
      },
      fail(err) {
        console.log(err);
      }
    })
  },
  // 监听socket事件
  listeningScoket() {
    let _this = this

    // 连接成功（连接成功,真正的成功）
    wx.onSocketOpen(() => {
      console.log('连接成功,真正的成功！');

      _this.data.socketOpen = true
      //  开始心跳
      _this.startHeartBeat()
    })

    // 监听webSocket错误
    wx.onSocketError(res => {
      // console.log(res);
      _this.data.socketOpen = false
    })

    // 监听连接关闭事件
    wx.onSocketClose(res => {
      console.log('监听连接关闭事件：', res);
      _this.data.socketOpen = false
    })

    // 服务器推送就会触发此方法，收到服务器内容
    wx.onSocketMessage(res => {
      // 心跳不处理
      if (res.data === '_this_is_socket_heart') return

      let _data = JSON.parse(res.data)
      console.log('服务器发送的数据：', _data);
      _this.data.commentList.push({
        jobName: _data.jobName,
        employeeName: _data.employeeName,
        comment: _data.comment,
      })
      _this.setData({
        commentList: _this.data.commentList
      })
    })
  },
  // socket开始心跳
  startHeartBeat() {
    let _this = this
    wx.sendSocketMessage({
      data: '_this_is_socket_heart',
      success(res) {
        console.log('socket心跳成功' + util.formatTime(Date.now(), 'yyyy-MM-dd hh:mm:ss'), res);
        _this.data.heartBeatTimeOut = setTimeout(() => {
          _this.startHeartBeat()
        }, 5000)
      },
      fail(res) {
        // console.log('socket心跳失败');
        _this.initSocket()
      },
    })
  },
  // 文字输入
  getReasonValue(e) {
    this.setData({
      comment: e.detail.value
    })
  },
  // 发送按钮
  sendMessage() {
    let _data = {
      jobName: '岗位名称',
      employeeName: '职务',
      comment: this.data.comment,
    }
    let _this = this
    wx.sendSocketMessage({
      data: JSON.stringify(_data),
      success(res) {
        console.log('发送成功：', res);
        _this.setData({
          comment: ''
        })
      },
      fail(res) {
        console.log('发送失败！');
      },
    })
  }
})